package com.zhengbo.flink.demo.base.utils;

import com.alibaba.fastjson.JSON;
import com.caocao.cdiamond.client.impl.DiamondSDKManagerImpl;
import com.caocao.cdiamond.domain.ContextResult;
import com.caocao.cdiamond.domain.DiamondConf;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.crypto.Cipher;
import javax.crypto.SecretKey;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.DESKeySpec;
import java.security.SecureRandom;
import java.util.Properties;

/**
 * <p>版权所有： 版权所有(C)2016-2099</p>
 * <p>公   司： 优行科技 </p>
 * <p>内容摘要： </p>
 * <p>其他说明： </p>
 * <p>完成日期：2017/10/30</p>
 *
 * @author 4kings
 * @version 1.0
 */
public class DESUtils {
    private final Logger logger = LoggerFactory.getLogger(DESUtils.class);

    private final static String DES = "DES";

    private  String password;

    private SecretKey secureKey = null;

    private Cipher cipher = null;

    private static volatile DESUtils instance;

    public static DESUtils getInstance(Properties properties){
        if (instance==null){
            synchronized (DESUtils.class){
                if (instance==null){
                    try {
                        instance=new DESUtils(properties);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            }
        }
        return instance;
    }

    public DESUtils(final String password) {
        this.password = password;
        this.init();
    }

    public DESUtils( Properties properties) throws Exception {
        this.password =getDesPassport(properties);
        this.init();
    }
    public String getDesPassport(Properties properties)throws Exception{
        checkProperties(properties);
        String serverId = "cdiamondmaven";
        String   diamondIp=properties.getProperty("diamond.ip");
        String   diamondPort=properties.getProperty("diamond.port");
        String   diamondUser=properties.getProperty("diamond.user");
        String   diamondPassword=properties.getProperty("diamond.password");
        DiamondConf diamondConf = new DiamondConf(diamondIp, diamondPort, diamondUser, diamondPassword);
        // 连接超时时间
        int connection_timeout = 8000;
        // 请求超时时间
        int require_timeout = 8000;
        DiamondSDKManagerImpl diamondManager = new DiamondSDKManagerImpl(connection_timeout, require_timeout);
        diamondManager.setDiamondConf(serverId, diamondConf);
        ContextResult result = diamondManager.queryByDataIdAndGroupName("risk.des.key","riskcenter",serverId);
        if (result == null || result.getConfigInfo()==null) {
            throw new  Exception("risk.desc.key is null");
        }
        if (logger.isInfoEnabled()){
            logger.info("diamond config :{}", JSON.toJSONString(result));
        }
       return  result.getConfigInfo().getContent();
    }


    private void checkProperties(Properties properties) throws Exception {
        if(properties==null){
            throw new Exception(" properties is null");
        }
        String   diamondIp=properties.getProperty("diamond.ip");
        String   diamondPort=properties.getProperty("diamond.port");
        String   diamondUser=properties.getProperty("diamond.user");
        String   diamondPassword=properties.getProperty("diamond.password");
        if(diamondIp==null ||diamondIp.length()<1){
            throw new Exception(" diamondIp is null");
        }
        /*if(diamondPort==null ||diamondPort.length()<1){
            throw new Exception(" diamondPort is null");
        }
        if(diamondUser==null ||diamondUser.length()<1){
            throw new Exception(" diamondUser is null");
        }
        if(diamondPassword==null ||diamondPassword.length()<1){
            throw new Exception(" diamondPassword is null");
        }*/
    }

    /**
     * 初始化
     */
    private void init() {
        try {
            DESKeySpec desKey = new DESKeySpec(password.getBytes());
            SecretKeyFactory keyFactory = SecretKeyFactory.getInstance(DES);
            secureKey = keyFactory.generateSecret(desKey);
            cipher = Cipher.getInstance(DES);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * 加密
     *
     * @param datasource 待加密数据
     * @return 加密结果
     */
    public byte[] encrypt(byte[] datasource) {
        SecureRandom random = new SecureRandom();
        byte[] result = null;
        try {
            cipher.init(Cipher.ENCRYPT_MODE, secureKey, random);
            result = cipher.doFinal(datasource);
        } catch (Exception e) {
            logger.error("encrypt|{}", new String(datasource));
        }
        return result;
    }

    /**
     * 解密
     *
     * @param src 待解密数据
     * @return 解密结果
     */
    public byte[] decrypt(byte[] src) {
        byte[] result = null;
        try {
            SecureRandom random = new SecureRandom();
            cipher.init(Cipher.DECRYPT_MODE, secureKey, random);
            result = cipher.doFinal(src);
        } catch (Exception e) {
            logger.error("decrypt|{}", new String(src));
        }
        return result;
    }

    public void close() {
        try {
            if (secureKey != null) {
//                securekey.destroy();
            }
        } catch (Exception e) {
            //ignore
        }
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }
}
